import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../models/device_model.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../translations/app_translations.dart';
import '../controllers/device_controller.dart';

class DeviceGridItem extends StatelessWidget {
  final Device device;
  final VoidCallback? onTap;
  final VoidCallback onActionTap;
  final VoidCallback onDetailsTap;
  final VoidCallback onDataTap;
  final VoidCallback? onDataTableTap;

  const DeviceGridItem({
    Key? key,
    required this.device,
    this.onTap,
    required this.onActionTap,
    required this.onDetailsTap,
    required this.onDataTap,
    this.onDataTableTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();
    
    print('设备完整信息: ${device.deviceId} - ${device.deviceName}');
    print('- 设备序列号: ${device.deviceSn}');
    print('- 设备图片URL: "${device.deviceImage}"');
    print('- 国标设备ID: "${device.wvpDeviceId}"');
    
    // 判断是否有国标ID
    bool hasWvpDevice = device.wvpDeviceId.isNotEmpty;
    
    return Card(
      elevation: 2,
      clipBehavior: Clip.antiAlias,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(extension?.cardRadius ?? 8),
        side: BorderSide(color: extension?.cardBorder ?? Colors.grey.shade200),
      ),
      child: InkWell(
        onTap: onDetailsTap,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                children: [
                  _buildDeviceStatusIcon(device.status),
                      // 移除这里的摄像头图标
                    ],
                  ),
                  IconButton(
                    icon: const Icon(Icons.more_vert, size: 18),
                    padding: EdgeInsets.zero,
                    constraints: const BoxConstraints(),
                    onPressed: onActionTap,
                  ),
                ],
              ),
              const SizedBox(height: 6),
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Container(
                  height: 65,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: theme.brightness == Brightness.dark 
                        ? Colors.grey.shade800 
                        : Colors.grey.shade200,
                  ),
                  child: Stack(
                    children: [
                      // 设备图片
                      Positioned.fill(
                  child: device.deviceImage.isNotEmpty
                      ? Image.network(
                          device.deviceImage,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) {
                            print('设备图片加载错误: $error');
                            print('错误的图片URL: "${device.deviceImage}"');
                            print('设备ID: ${device.deviceId}, 设备名称: ${device.deviceName}');
                            return _buildDefaultDeviceImage(theme, device.status);
                          },
                          loadingBuilder: (context, child, loadingProgress) {
                            if (loadingProgress == null) {
                              print('设备图片加载成功: ${device.deviceName}');
                              return child;
                            }
                            
                            return Center(
                              child: CircularProgressIndicator(
                                value: loadingProgress.expectedTotalBytes != null
                                    ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                                    : null,
                                strokeWidth: 2,
                              ),
                            );
                          },
                        )
                      : _buildDefaultDeviceImage(theme, device.status),
                      ),
                      
                      // 国标摄像头图标（右上角）
                      if (hasWvpDevice)
                        Positioned(
                          top: 5,
                          right: 5,
                          child: Container(
                            padding: const EdgeInsets.all(4),
                            decoration: BoxDecoration(
                              color: Colors.red.withOpacity(0.8),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: InkWell(
                              onTap: () {
                                print('国标监控设备ID: ${device.wvpDeviceId}');
                              },
                              child: const Icon(
                                Icons.videocam,
                                color: Colors.white,
                                size: 16,
                              ),
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
              const SizedBox(height: 6),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      device.deviceName ?? LocaleKeys.unnamedDevice.tr,
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                        fontSize: 12,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    Flexible(
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              '${LocaleKeys.serialNumber.tr}: ${device.deviceSn}',
                              style: theme.textTheme.bodyMedium?.copyWith(
                                color: extension?.textSecondary,
                                fontSize: 10,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Flexible(
                      child: Text(
                        '${LocaleKeys.product.tr}: ${device.productName ?? LocaleKeys.unknownProduct.tr}',
                        style: theme.textTheme.bodyMedium?.copyWith(
                          color: extension?.textSecondary,
                          fontSize: 10,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 3),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  _buildStatusChip(device.status),
                  
                  Row(
                    children: [
                      // 添加摄像头图标（如果设备有国标监控ID）
                      if (hasWvpDevice) ...[
                        SizedBox(
                          width: 30,
                          height: 30,
                          child: OutlinedButton(
                            onPressed: () {
                              Get.find<DeviceController>().viewDeviceVideo(device.deviceId);
                            },
                            style: OutlinedButton.styleFrom(
                              padding: EdgeInsets.zero,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(4), 
                              ),
                              side: BorderSide(color: Colors.red.withOpacity(0.7)),
                            ),
                            child: const Icon(Icons.videocam, size: 14, color: Colors.red),
                          ),
                        ),
                        const SizedBox(width: 4),
                      ],
                      
                      SizedBox(
                        width: 30,
                        height: 30,
                        child: OutlinedButton(
                          onPressed: onDataTap,
                          style: OutlinedButton.styleFrom(
                            padding: EdgeInsets.zero,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(4), 
                            ),
                            side: BorderSide(color: theme.primaryColor.withOpacity(0.5)),
                          ),
                          child: Icon(Icons.show_chart, size: 14, color: theme.primaryColor),
                        ),
                      ),
                      
                      if (onDataTableTap != null) ...[
                        const SizedBox(width: 4),
                        SizedBox(
                          width: 30,
                          height: 30,
                          child: OutlinedButton(
                            onPressed: onDataTableTap,
                            style: OutlinedButton.styleFrom(
                              padding: EdgeInsets.zero,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(4), 
                              ),
                              side: BorderSide(color: theme.primaryColor.withOpacity(0.5)),
                            ),
                            child: Icon(Icons.table_chart, size: 14, color: theme.primaryColor),
                          ),
                        ),
                      ],
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  Widget _buildDeviceStatusIcon(int? status) {
    IconData iconData;
    Color iconColor;
    
    switch (status) {
      case 0: // 未激活
        iconData = Icons.device_unknown;
        iconColor = Colors.grey;
        break;
      case 1: // 在线
        iconData = Icons.check_circle_outline;
        iconColor = Colors.green;
        break;
      case 2: // 离线
        iconData = Icons.offline_bolt;
        iconColor = Colors.orange;
        break;
      case 3: // 禁用
        iconData = Icons.block;
        iconColor = Colors.red;
        break;
      default:
        iconData = Icons.device_unknown;
        iconColor = Colors.grey;
    }
    
    final Color bgColor = Color.fromRGBO(
      iconColor.red, 
      iconColor.green, 
      iconColor.blue, 
      0.16
    );
    
    return CircleAvatar(
      backgroundColor: bgColor,
      radius: 16,
      child: Icon(iconData, color: iconColor, size: 18),
    );
  }
  
  Widget _buildStatusChip(int? status) {
    final theme = Get.theme;
    final extension = theme.extension<AppThemeExtension>();
    
    String label;
    Color color;
    Color textColor = Colors.white;
    
    switch (status) {
      case 0: // 未激活
        label = LocaleKeys.deviceInactive.tr;
        color = extension?.disabledBg ?? Colors.grey.shade200;
        textColor = extension?.disabledText ?? Colors.grey;
        break;
      case 1: // 在线
        label = LocaleKeys.deviceOnline.tr;
        color = extension?.successBg ?? Colors.green.shade100;
        textColor = extension?.successText ?? Colors.green;
        break;
      case 2: // 离线
        label = LocaleKeys.deviceOffline.tr;
        color = extension?.warningBg ?? Colors.orange.shade100;
        textColor = extension?.warningText ?? Colors.orange;
        break;
      case 3: // 禁用
        label = LocaleKeys.deviceDisabled.tr;
        color = extension?.errorBg ?? Colors.red.shade100;
        textColor = extension?.errorText ?? Colors.red;
        break;
      default:
        label = LocaleKeys.statusUnknown.tr;
        color = extension?.disabledBg ?? Colors.grey.shade200;
        textColor = extension?.disabledText ?? Colors.grey;
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Text(
        label, 
        style: TextStyle(
          color: textColor, 
          fontSize: 10,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  Widget _buildDefaultDeviceImage(ThemeData theme, int? status) {
    IconData iconData;
    Color iconColor;
    
    switch (status) {
      case 0: // 未激活
        iconData = Icons.device_unknown;
        iconColor = Colors.grey;
        break;
      case 1: // 在线
        iconData = Icons.check_circle_outline;
        iconColor = Colors.green;
        break;
      case 2: // 离线
        iconData = Icons.offline_bolt;
        iconColor = Colors.orange;
        break;
      case 3: // 禁用
        iconData = Icons.block;
        iconColor = Colors.red;
        break;
      default:
        iconData = Icons.devices;
        iconColor = theme.primaryColor;
    }
    
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            iconData,
            color: iconColor,
            size: 28,
          ),
          const SizedBox(height: 2),
          Text(
            '设备',
            style: TextStyle(
              color: theme.brightness == Brightness.dark 
                  ? Colors.grey.shade400 
                  : Colors.grey.shade600,
              fontSize: 10,
            ),
          ),
        ],
      ),
    );
  }
} 